package cn.hyh.core.service.impl;

import cn.hyh.core.component.GlobalStatus;
import cn.hyh.core.dao.ContentMapper;
import cn.hyh.core.dao.MsgMapper;
import cn.hyh.core.dao.VisitHistoryMapper;
import cn.hyh.core.pojo.Msg;
import cn.hyh.core.pojo.VisitHistory;
import cn.hyh.core.util.HttpUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.validation.constraints.Email;
import java.util.Date;

/**
 * @auther :hyh
 * @desc :     异步方法。
 * @date :2019/7/21
 */
@Service
public class AsyncServiceImpl {
    @Value("${ip.api}")
    private  String ipUrl;

    @Resource
    private VisitHistoryMapper visitHistoryMapper;

    @Resource
    private MsgMapper msgMapper;

    @Resource
    private JavaMailSender javaMailSender;
    @Async
    public void saveHistory(String realIp) {
        String address = getAddressByIP(realIp);
        VisitHistory history = new VisitHistory();
        history.setAddress(address).setIp(realIp).setCreateTime(new Date());
        visitHistoryMapper.insert(history);
    }

    //获取ip,失败返回未知
    public  String getAddressByIP(String ip) {
        String result = HttpUtils.GET(ipUrl + ip);
        System.out.println("执行异步方法"+result);
        String address = "未知";
        if (StringUtils.isNoneBlank(result)) {
            JSONObject object = JSON.parseObject(result);
            int code = object.getIntValue("code");
            if (code == 0) {
                //解析成功！
                JSONObject data = object.getJSONObject("data");
                address = data.getString("region") + "," + data.getString("city");
            }
        }

        return  address;
    }

    /**
     *   发送对应的短信。。。
     * @param msg
     * @param status
     */
    @Async
    public void sendToHost(Msg msg, int status) {
        System.out.println("发送邮件===>");
        if (status == GlobalStatus.OTHER_TO_OTHER) {
            //发送给别人
            int parent = msg.getParent();
            Msg parentMsg = msgMapper.selectById(parent);
            if (MsgServiceImpl.checkEmail(msg.getEmail()) && MsgServiceImpl.checkEmail(parentMsg.getEmail())) {
                //二者都email 检查正确，就给他发消息。
                StringBuilder sb = new StringBuilder();
                sb.append("你在HYH博客的评论：" +"<span style='color:red'>"+parentMsg.getContent()+"</span>被回复啦！<br/>");
                sb.append("回复者昵称：" + msg.getNickName()+"<br/>");
                sb.append("回复内容：" +"<span style='color:red'>"+msg.getContent()+"</span><br/>");
                sb.append("回复者者邮箱:<span style='text-decoration: underline;color:red'>"+msg.getEmail()+"</span>");
                try {
                    sendEmail(sb.toString(),"博客回复通知:",parentMsg.getEmail());
                } catch (MessagingException e) {
                    e.printStackTrace();
                }
            }
        }else {
             //发送给自己。
            StringBuilder sb = new StringBuilder();
            sb.append("评论者昵称：" + msg.getNickName()+"<br/>");
            sb.append("评论内容：" +"<span style='color:red'>"+msg.getContent()+"</span><br/>");
            sb.append("评论者邮箱:<span style='text-decoration: underline;color:red'>"+msg.getEmail()+"</span>");
            try {
                sendEmail(sb.toString(),"博客评论通知:","1046522830@qq.com");
            } catch (MessagingException e) {
                e.printStackTrace();
            }

        }
    }


    public void sendEmail(String content,String subject,String toUser) throws MessagingException {
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message,true);
        helper.setFrom("heyihui104622830@163.com");
        helper.setTo(toUser);
        helper.setSubject(subject);
        helper.setText(content,true);
        javaMailSender.send(message);
    }
}
